package com.ymj.netty.client.handler;

import com.alibaba.fastjson.JSONObject;
import com.ymj.netty.client.ClientFuture;
import com.ymj.netty.common.Response;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.apache.commons.lang.StringUtils;
/**
 *  @Description:
 *  @author: yanmj
 *  @Date: 2020-06-07
 */
@ChannelHandler.Sharable  /*表示一个ChannelHandler可以被多个Channel安全共享*/
public class BizClientHandler extends SimpleChannelInboundHandler<String> {


    @Override
    public void channelActive(ChannelHandlerContext ctx){
        System.out.println("连上服务器! ");
        //ctx.channel().writeAndFlush("hello,server! \r\n");

    }

    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String s) throws Exception {
        System.out.println("Client received:["+ s +"]");
        if(StringUtils.isBlank(s)){
            return;
        }
        if("ping".equals(s)){
            //心跳处理
            channelHandlerContext.channel().writeAndFlush("pong\r\n");
            return ;
        }
        //接收到服务端的响应并处理
        Response response = JSONObject.parseObject(s,Response.class);
        ClientFuture.receive(response);
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        super.channelReadComplete(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
    }


}
